using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Cryptography ;

namespace MACL
{
    [ComVisible(true)]
    [Guid("ECC9A6B4-156F-4e01-A413-6B2AEBD369CA")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("m3Cryptographie")]
    public class m3Cryptographie : Im3Cryptographie
    {
        public string EncryptString(string StringToEncrypt, string MyKey)
        {
            try
            {
                //string MyKey = "{12, 26, 13, 44, 95, 16, 17, 38, 29, 10, 11, 22, 43, 24, 15, 56, 37, 78, 29, 27, 23, 52, 43, 4}";
                byte[] keyArray;
                byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(StringToEncrypt);

                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(MyKey));

                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                tdes.Key = keyArray;
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;

                ICryptoTransform cTransform = tdes.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public string DecryptString(string StringToDecrypt, string MyKey)
        {
            try
            {
                //string MyKey = "{12, 26, 13, 44, 95, 16, 17, 38, 29, 10, 11, 22, 43, 24, 15, 56, 37, 78, 29, 27, 23, 52, 43, 4}";
                byte[] keyArray;
                byte[] toEncryptArray = Convert.FromBase64String(StringToDecrypt);

                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(MyKey));

                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                tdes.Key = keyArray;
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;

                ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception)
            {
                throw;
            } 
        }
    }
}
